package com.reggie.interceptor;

import com.reggie.annotation.IgnoreToken;
import com.reggie.constant.JwtClaimsConstant;
import com.reggie.context.BaseContext;
import com.reggie.properties.JwtProperties;
import com.reggie.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局拦截器处理
 */
@Slf4j
@Component
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到请求：{}" + request.getRequestURI());

        if (!(handler instanceof HandlerMethod)){
            //如果不是映射到controller某个方法的请求，则直接放行，例如请求的是/doc.html,就是静态页面就直接放行
            return true;
        }

        //判断此方法是否是自定义注解修饰的，如果是，则放行
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        boolean hasMethodAnnotation = handlerMethod.hasMethodAnnotation(IgnoreToken.class);
        if (hasMethodAnnotation){
            //加入了IgnoreToken注解，直接放行
            return true;
        }

        //1、获取token
        String token = request.getHeader(jwtProperties.getUserTokenName());

        try {
            //2、解析token
            //3、判断token是否正确，如果正确，就放行
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            //获取当前登录员工的ID
            Long userId = Long.valueOf( claims.get(JwtClaimsConstant.USER_ID).toString());
            //保存当前登录员工的id到线程本地变量
            BaseContext.setCurrentId(userId);
            return true;

        } catch (Exception e) {
            //4、如果不正确，就返回401给前端
            response.setStatus(401);
            return false;
        }
    }
}
